<?php
/**
 * Created by PhpStorm.
 * User: stiff <1570004138@163.com>
 * Date: 2017/5/24
 * Time: 9:22
 */
namespace app\home\controller;
use think\Controller;
use app\home\model\WechatUser;
use think\Cookie;
use think\Session;
use think\Config;

class Verify extends Controller{
    public function _initialize(){
        //判断是否味微信打开
//        $this ->oauth();
        //cookie初始化
        Cookie::init(Config::get('cookie'));
    }
    /**
     *账号密码登陆
     */
    public function login(){
        //判断是否味微信打开
//        $this ->oauth();
        $phone = input('phone');
        $user = new WechatUser();
        $map = ['mobile' => $phone,'state' => 1];
        $result = $user->where($map)->find();
        //账户正确
        if($result){
            Cookie::clear('ycxpb');
            session('userId',null);
            //第一次登陆 初始userId
            if(empty($result['userid']))
            {
                $id = md5(uniqid());//不重复随机id
                Cookie::set('ycxpb',['user' =>$id]);
                $user ->save( ['userid' => $id,'status' => 1] , ['mobile' => $phone,'state' => 1]);
            }else{
                Cookie::set('ycxpb',['user' =>$result['userid']]);
            }
            //登陆后跳转判断
            if(Session::has('url'))
            {
                $url = session('url');
                Session::delete('url');//跳转后清空
            }else{
                $url = '';
            }
            return $this ->success('登录成功!',$url);
        }else{
            $this ->error('账号错误!');
        }
    }

    /**
     * 判断是否微信打开
     */
    public function oauth(){
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false)
        {
            // 非微信浏览器禁止浏览
            $this ->error('请在微信打开!');
        } else {
            // 微信浏览器，允许访问
            // 获取版本号
            preg_match('/.*?(MicroMessenger\/([0-9.]+))\s*/', $user_agent, $matches);
        }
    }
    /**
     * 退出登录
     */
    public function logout(){
        //cookie初始化 session 初始化
        Cookie::delete('ycxpb');
        session('userId',null);
        return $this ->fetch('loginindex');
    }
    /**
     * 游客登录
     */
    public function tourist(){
        //cookie初始化 session 初始化
        Cookie::delete('ycxpb');
        session('userId','visitor');
        session('url','/home/index/index');
        return $this ->redirect(session('url'));
    }

    /**
     * 带游客模式的登录页
     * @return mixed
     */
    public function loginindex(){
        return $this ->fetch();
    }

    public function null(){
        return $this ->fetch();
    }
}